import axios from 'axios';
import {getToken, getLocalLang, loyout} from "@/utils/index";
import { Toast,Dialog  } from 'vant';
import {errInfoCh} from "./errorCh";
import {errInfoEn} from "./errorEn";

const afterSuccess=(arg)=>{
  if(window.requestAfterSuccess){
    try{
      window.requestAfterSuccess(arg)
    }catch (e) {}
  }
}
let errInfo=window.system_localLang==='ch'?errInfoCh:errInfoEn;

const baseUrl=process.env.NODE_ENV === 'production'?window.system_baseUrl:'/api/';

export default function ({url='',service='cms-service',method='',data={},fullUrl,headers={}}) {
  return new Promise((resolve, reject)=>{
    let obj={
      url:fullUrl? fullUrl : baseUrl+service + url,
      method:method.toLowerCase(),
      headers:{
        // Authorization:'Bearer '+getToken(),
        ...headers
      }
    }
    if(method.toLowerCase()==='get'){
      obj.params=data
    }else {
      obj.data=data
    }
    axios(obj).then((res) => {
      // console.log('%c'+method+' %c'+url,'color: blue;','color: green;',data,'=>',res.data)
      if(res.data.code=='500'||res.data.code=='400'){
        reject()
        Toast(res.data.msg||'系统错误')
      }else {
        afterSuccess({url,method,data,fullUrl})
        resolve(res.data)
      }
    }).catch((err) => {
      // console.log('%c失败 '+url,'color: red;',data,'=>',err)
      reject()
      if(err.response?.data?.code!='400'&&err.response?.data?.code!='500'&&errInfo[err.response?.data?.code]){
        if(err.response?.data?.code=='401'){
          Toast(errInfo[err.response?.data?.code]||'系统错误')
          setTimeout(() => {
            loyout()
          },400)
        }else {
          Dialog({
            title:errInfo[err.response?.data?.code]||'系统错误'
          })
        }
      }else {
        Toast(err.response?.data?.msg||'系统错误')
      }
    })
  })
}
